package com.example.nextgen.function;

import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 函数管理器
 */
@Component
public class FunctionManager {

    @Resource
    List<ExtendFunction> functions;

    public Object invoke(ExtendFunction extendFunction,String function,String parameter){
        AtomicReference<Object> result = new AtomicReference<>("");
        if (extendFunction != null){
            Method method;
            try {
                method = extendFunction.getClass().getMethod(function, String.class);
                result.set(method.invoke(extendFunction, parameter));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result.get();
    }

    public Object invoke(String object,String function,String parameter){
        ExtendFunction extendFunction = getFunction(object);
        return invoke(extendFunction,function,parameter);
    }

    public ExtendFunction getFunction(String object){
        return functions.stream().filter(extendFunction -> {
            Class<? extends ExtendFunction> functionClass = extendFunction.getClass();
            return functionClass.getSimpleName().equalsIgnoreCase(object);
        }).findFirst().get();
    }


}
